import axios from 'axios'
import Cookies from 'js-cookie'
import uuid from 'uuid-v4'
import isTokenExpired from './util.js'
import { showLoading, hideLoading } from './loading.js'
import
{
    reflogintoken
}
from '@/libs/reqlist.js'

let isRefreshing = false
let base = '/sys'
let detLang = navigator.language

let requests = []
let token = ''
let syslanguage = Cookies.get('language') || detLang

axios.interceptors.request.use(
    config => {
        if (config.url !== '/checkcode/img' && config.url !== '/token/refresh') {
            showLoading()
        }
        if (isTokenExpired() && config.url !== '/checkcode/img' && config.url !== '/login' && config.url !== '/token/refresh') {
            if (!isRefreshing) {
                isRefreshing = true
                let reftoken = window.localStorage.getItem('refreshToken')
                reflogintoken({ refreshToken: reftoken }).then(res => {
                    isRefreshing = false
                    token = res.data.data.token
                    window.localStorage.setItem('token', token)
                    window.localStorage.setItem('refreshToken', res.data.data.refreshToken)
                    let update = new Date().getTime()
                    window.sessionStorage.setItem('refTime', update)
                }).then(() => {
                    requests.forEach(cb => cb(token))
                    /* 执行onRefreshed函数后清空数组中保存的请求 */
                    requests = []
                })
            }
            /* 把请求(token)=>{....}都push到一个数组中 */
            let retry = new Promise((resolve) => {
                /* (token) => {...}这个函数就是回调函数 */
                requests.push(() => {
                    config.headers['comParam'] = '{"device_id":"012315","device_type":"IOS","os_type":"v1.0","os_version":"v1.0","serial_no":"' + uuid().split('-').join('') + '","token":"' + token + '","sysLanguage": "' + syslanguage + '"}'
                    /* 将请求挂起 */
                    resolve(config)
                })
            })
            return retry
        }
        return config
    })

axios.interceptors.response.use(
    response => {
        hideLoading()
        const { code } = response.data
        if (code === '991001') {
            window.vm.$message.error(window.vm.$t('accisloginelsewhere'))
            window.localStorage.removeItem('token')
            window.localStorage.removeItem('autologin')
            window.localStorage.removeItem('refreshToken')
            window.sessionStorage.clear()
            window.vm.$router.push('/login')
        }
        if (code === '999902') {
            window.vm.$message.error(window.vm.$t('sysisbusy'))
        }
        if (code === '020002') {
            window.localStorage.removeItem('token')
            window.localStorage.removeItem('autologin')
            window.localStorage.removeItem('refreshToken')
            window.sessionStorage.clear()
            window.vm.$message.error(window.vm.$t('plslgnagn'))
            window.vm.$router.push('/login')
        }
        if (code === '050001') {
            window.vm.$message.error(window.vm.$t('Inuserrights'))
        }
        return response
    }, err => {
        hideLoading()
        if (err.message.indexOf('timeout') === 0) {
            window.vm.$message.error(window.vm.$t('therequesttimeout'))
        }
        if (err.message.indexOf('Network Error') === 0) {
            window.vm.$message.error(window.vm.$t('netwkisue'))
        }
        if (err.response.data.status === 404) {
            window.vm.$message(window.vm.$t('funcdev'))
        }
        return err
    })

export const postRequest = (url, data, type) => {
    let accessToken = window.localStorage.getItem('token')
    return axios({
        method: 'post',
        baseURL: base,
        url,
        data: data,
        timeout: 20000,
        headers: {
            'Content-Type': type,
            'comParam': '{"device_id":"012315","device_type":"IOS","os_type":"v1.0","os_version":"v1.0","serial_no":"' + uuid().split('-').join('') + '","token":"' + accessToken + '","sysLanguage": "' + syslanguage + '"}'
        }
    })
}

export const getRequest = (url, params) => {
    let accessToken = window.localStorage.getItem('token')
    return axios({
        method: 'get',
        baseURL: base,
        url,
        params,
        timeout: 20000,
        headers: {
            'comParam': '{"device_id":"012315","device_type":"IOS","os_type":"v1.0","os_version":"v1.0","serial_no":"' + uuid().split('-').join('') + '","token":"' + accessToken + '","sysLanguage": "' + syslanguage + '"}'
        }
    })
}

export const deleteRequest = (url, data, type) => {
    let accessToken = window.localStorage.getItem('token')
    return axios({
        method: 'delete',
        baseURL: base,
        url,
        data: data,
        timeout: 20000,
        headers: {
            'Content-Type': type,
            'comParam': '{"device_id":"012315","device_type":"IOS","os_type":"v1.0","os_version":"v1.0","serial_no":"' + uuid().split('-').join('') + '","token":"' + accessToken + '","sysLanguage": "' + syslanguage + '"}'
        }
    })
}
